#!/usr/bin/python


from django.template import  loader
from django.template import Template, Context
from django.conf import settings
from optparse import OptionParser
import os
from ID3 import *
import string
from operator import *

#constants
MP3_FILE_INDEX = 0
MP3_TITLE_INDEX = 1
MP3_ARTIST_INDEX = 2
MP3_ALBUM_INDEX = 3


unsafe_chars = "/#()[]!@$%^&*{}\'\"`?<>| \t\n\x00"
alt_chars = "__________________________"
trans_table = string.maketrans(unsafe_chars, alt_chars)

mp3Container = []

def load_arguments():
    usage = " python xspfgen -f filename |--file=filename [options]  "
    parser = OptionParser(usage)
    parser.add_option("-r", "--rootdir", dest="rootdir", default="./",
                      help="Rootdir where the mp3 files or stored")
    parser.add_option("-t", "--templatedir", dest="templatedir", default="./",
                       help="directory where the template files are located")
    parser.add_option("-x", "--xspf_template",  dest="xspf_template", default = "xspf_template.xspf" ,
                       help=" Template file for XSPF. ")
    parser.add_option("-w", "--webpage_template", dest="webpage_template", default ="playlist_template.html",
                       help=" template to generate webpage")
    parser.add_option("-s", "--output_hxspf_file",  dest="output_xspf_file", default="my.xspf",
                       help=" htnl output filename. Default is index.html")
    parser.add_option("-o", "--output_html_file",  dest="output_html_file", default="index.html",
                       help=" htnl output filename. Default is index.html")
    parser.add_option("-b", "--baseuri",  dest="baseuri", default="http://localhost/",
                       help=" URL name ")
    
    (options, args) = parser.parse_args()
    print options
    #print args
       
    return options

def FilterMp3Files(container, dir, filenames):
    #print dir
    if "./" == dir:
        mp3files = ['/'+mp3file for mp3file in filenames if ".mp3" == os.path.splitext(mp3file)[1].lower() and os.path.isfile(dir+'/'+mp3file)]
    else:
        mp3files = [dir[1:]+'/'+mp3file for mp3file in filenames if ".mp3" == os.path.splitext(mp3file)[1].lower() and os.path.isfile(dir+'/'+mp3file)]
    # if there no mp3 files  in this directory return
    if not mp3files:
        return
    
    #print mp3files
    
    # Now extract the ID tag information from the MP3 files and store it as a tuple in mp3_info_list variable
   
    for f in mp3files:
        id3 = ID3("./"+f)
        l = (f, id3.title.translate(trans_table), id3.artist.translate(trans_table), id3.album.translate(trans_table))
        mp3Container.append(l)
    
    

def  BuildPlayList(baseDir):
     os.path.walk(baseDir, FilterMp3Files, None)

def GenerateOutput(filename, content):
    try:
        handle = open(filename, 'w')
    except IOError:
        print" File IO Error \n",
        sys.exit()
        
    handle.write(content)
    handle.close()
    return

def cmp ( c1, c2):
    if c1 == c2:
        return c1
    
        
def main():
    
    options = load_arguments()
    
    if ( options == None ):
        print "Load Options Failed\n"
        exit
    
    settings.configure (DEBUG=True, TEMPLATE_DEBUG=True, \
                       TEMPLATE_LOADERS = ('django.template.loaders.filesystem.load_template_source', \
                                           'django.template.loaders.app_directories.load_template_source'),\
                                            TEMPLATE_DIRS=(options.templatedir, options.templatedir))

    BuildPlayList(options.rootdir)
    
    # all Songs
    template_context = { 'path':options.baseuri,
                         'mp3Container': mp3Container}
    text = loader.render_to_string(options.xspf_template, Context(template_context))
    GenerateOutput(options.output_xspf_file, text)

    template_context = { 'base_url':options.baseuri, 'xspf_playlist':options.output_xspf_file}
    text = loader.render_to_string(options.webpage_template, Context(template_context))
    GenerateOutput('all.html', text)

    html_list = []
    html_list.append('all.html')
    #Categorised based on Albums
    container_sorted_on_album = sorted(mp3Container, key=itemgetter(MP3_ALBUM_INDEX))
    album_names = [l[MP3_ALBUM_INDEX] for l in container_sorted_on_album if l[MP3_ALBUM_INDEX] != '']
    album_keys = dict.fromkeys(album_names).keys()
    for a_key in album_keys:
        a_list = [t for t in container_sorted_on_album if t[MP3_ALBUM_INDEX] == a_key] 
        template_context = { 'path':options.baseuri,
                         'mp3Container': a_list}
        text = loader.render_to_string(options.xspf_template, Context(template_context))
        GenerateOutput(a_key+'.xspf', text)
        
        template_context = { 'base_url':options.baseuri, 'xspf_playlist':a_key+'.xspf'}
        text = loader.render_to_string(options.webpage_template, Context(template_context))
        GenerateOutput(a_key+'.html', text)
        html_list.append(a_key+'.html')
    
    
    #Categorised based on Artist
    container_sorted_on_artist = sorted(mp3Container, key=itemgetter(MP3_ARTIST_INDEX))
    artist_names = [l[MP3_ARTIST_INDEX] for l in container_sorted_on_artist if l[MP3_ARTIST_INDEX] != '']
    artist_keys = dict.fromkeys(artist_names).keys()
    for a_key in artist_keys:
        a_list = [t for t in container_sorted_on_artist if t[MP3_ARTIST_INDEX] == a_key] 
        template_context = { 'path':options.baseuri,
                         'mp3Container': a_list}
        text = loader.render_to_string(options.xspf_template, Context(template_context))
        GenerateOutput(a_key+'.xspf', text)
        
        template_context = { 'base_url':options.baseuri, 'xspf_playlist':a_key+'.xspf'}
        text = loader.render_to_string(options.webpage_template, Context(template_context))
        GenerateOutput(a_key+'.html', text)
        html_list.append(a_key+'.html')
    
    
    template_context = { 'base_url':options.baseuri, 'html_list':html_list}
    text = loader.render_to_string("index_template.html", Context(template_context))
    print text
    GenerateOutput(options.output_html_file, text)
    
    
if __name__ == "__main__":
    main()
